<template>
  <div class="upload-image">
    <el-upload
      class="image-uploader"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <img v-if="modelValue" :src="getFullImageUrl(modelValue)" class="uploaded-image" />
      <el-icon v-else class="upload-icon"><Plus /></el-icon>
      <div v-if="!modelValue" class="upload-text">
        <div>点击上传图片</div>
        <div class="upload-tip">支持 JPG、PNG 格式，建议尺寸 800x600</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

export default {
  name: 'UploadImage',
  components: {
    Plus
  },
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const uploadUrl = computed(() => {
      const baseUrl = 'https://dpcurdgwzmkg.sealosbja.site'
      return `${baseUrl}/api/v1/admin/upload`
    })

    const uploadHeaders = computed(() => ({
      'Authorization': `Bearer ${localStorage.getItem('admin_token')}`
    }))

    const beforeUpload = (file) => {
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPGorPNG) {
        ElMessage.error('图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    const handleSuccess = (response) => {
      if (response.code === 200) {
        emit('update:modelValue', response.data.url)
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error(response.message || '图片上传失败')
      }
    }

    const handleError = () => {
      ElMessage.error('图片上传失败')
    }

    const getFullImageUrl = (url) => {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/')) return $imageBaseUrl.value + url;
      return `${$imageBaseUrl.value}${url.startsWith('/') ? '' : '/'}${url}`;
    }

    const $imageBaseUrl = computed(() => {
      return process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn';
    })

    return {
      uploadUrl,
      uploadHeaders,
      beforeUpload,
      handleSuccess,
      handleError,
      getFullImageUrl,
      $imageBaseUrl
    }
  }
}
</script>

<style scoped>
.upload-image {
  width: 100%;
}

.image-uploader {
  width: 300px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.image-uploader:hover {
  border-color: #409eff;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.upload-text {
  text-align: center;
  color: #8c939d;
}

.upload-tip {
  font-size: 12px;
  margin-top: 5px;
  color: #999;
}
</style> 